<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
    :disabled="disabled"
  >
    <el-table :data="formData" show-summary :summary-method="getSummaries" class="-mt-10px">
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column label="仓库名称" min-width="125">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.warehouseId`"
            :rules="formRules.warehouseId"
            class="mb-0px!"
          >
            <el-select
              v-model="row.warehouseId"
              clearable
              filterable
              placeholder="请选择仓库"
              @change="onChangeWarehouse($event, row)"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" min-width="180">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productName" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="库存" min-width="100">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.stockCount" :formatter="erpCountInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="金成色" min-width="150">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productBarCode" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="品目" min-width="80">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productUnitName" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="品类" min-width="80">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productCategoryName" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="克重" min-width="100">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.weight" :formatter="erpCountInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column
        label="已出库"
        fixed="right"
        min-width="80"
        v-if="formData[0]?.outCount != null"
      >
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.outCount" :formatter="erpCountInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column
        label="已退货"
        fixed="right"
        min-width="80"
        v-if="formData[0]?.returnCount != null"
      >
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.returnCount" :formatter="erpCountInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="数量" prop="count" fixed="right" min-width="140">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">
            <el-input-number
              v-model="row.count"
              controls-position="right"
              :min="0.001"
              :precision="3"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="总克重" min-width="100">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.totalWeight" :formatter="erpCountInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品单价" fixed="right" min-width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productPrice`" class="mb-0px!">
            <el-input-number
              v-model="row.productPrice"
              controls-position="right"
              :min="0.01"
              :precision="2"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="金额" prop="totalProductPrice" fixed="right" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.totalProductPrice`" class="mb-0px!">
            <el-input
              disabled
              v-model="row.totalProductPrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="税率（%）" fixed="right" min-width="115">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.taxPercent`" class="mb-0px!">
            <el-input-number
              v-model="row.taxPercent"
              controls-position="right"
              :min="0"
              :precision="2"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="税额" prop="taxPrice" fixed="right" min-width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.taxPrice`" class="mb-0px!">
            <el-form-item :prop="`${$index}.taxPrice`" class="mb-0px!">
              <el-input disabled v-model="row.taxPrice" :formatter="erpPriceInputFormatter" />
            </el-form-item>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="税额合计" prop="totalPrice" fixed="right" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.totalPrice`" class="mb-0px!">
            <el-input disabled v-model="row.totalPrice" :formatter="erpPriceInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button :disabled="formData.length === 1" @click="handleDelete($index)" link>
            —
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
</template>
<script setup lang="ts">
import {
  erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  getSumValue
} from '@/utils'
import { GoldWarehouseApi, GoldWarehouseVO } from '@/api/gold/warehouse'
import { ProductApi, ProductVO } from '@/api/erp/product/product'

const props = defineProps<{
  items: undefined
  disabled: false
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '产品数量不能为空', trigger: 'blur' }]
})
const formRef = ref([]) // 表单 Ref
const warehouseList = ref<GoldWarehouseVO[]>([]) // 仓库列表
const defaultWarehouse = ref<GoldWarehouseVO>(undefined) // 默认仓库
const productList = ref<ProductVO[]>([]) // 产品列表

/** 初始化设置出库项 */
watch(
  () => props.items,
  async (val) => {
    console.log('SaleReturnItemForm - props.items:', val) // 调试信息
    if (val && val.length > 0) {
      // 确保每个项目都有必要的字段
      const mappedData = await Promise.all(
        val.map(async (item) => {
          console.log('SaleReturnItemForm - item:', item) // 调试信息

          // 如果有productId，获取完整的产品信息
          if (item.productId) {
            try {
              const product = await ProductApi.getProduct(item.productId)
              console.log('SaleReturnItemForm - fetched product:', product) // 调试信息

              return {
                ...item,
                productCategoryName:
                  product.unitName || item.productCategoryName || item.productName || '', // 品类
                productUnitName:
                  product.categoryName || item.productUnitName || item.categoryName || '', // 品目
                productBarCode:
                  product.goldFinenessName || item.productBarCode || item.goldFinenessName || '', // 金成色
                stockCount:
                  product.stock || item.stock || item.stockCount || item.productStock || 0, // 库存
                weight: product.weight || item.weight || item.productWeight || 0, // 克重
                totalWeight:
                  item.totalWeight ||
                  erpPriceMultiply(product.weight || item.weight || 0, item.count || 0), // 总克重
                productPrice: product.salePrice || item.productPrice || 0 // 销售价格
              }
            } catch (error) {
              console.error('SaleReturnItemForm - Error fetching product:', error)
              // 如果获取失败，使用原有数据
              return {
                ...item,
                productCategoryName: item.productCategoryName || item.productName || '', // 品类
                productUnitName: item.productUnitName || item.categoryName || '', // 品目
                productBarCode: item.productBarCode || item.goldFinenessName || '', // 金成色
                stockCount: item.stock || item.stockCount || item.productStock || 0, // 库存
                weight: item.weight || item.productWeight || 0, // 克重
                totalWeight: item.totalWeight || erpPriceMultiply(item.weight || 0, item.count || 0) // 总克重
              }
            }
          } else {
            // 没有productId，使用原有映射逻辑
            return {
              ...item,
              productCategoryName: item.productCategoryName || item.productName || '', // 品类
              productUnitName: item.productUnitName || item.categoryName || '', // 品目
              productBarCode: item.productBarCode || item.goldFinenessName || '', // 金成色
              stockCount: item.stock || item.stockCount || item.productStock || 0, // 库存
              weight: item.weight || item.productWeight || 0, // 克重
              totalWeight: item.totalWeight || erpPriceMultiply(item.weight || 0, item.count || 0) // 总克重
            }
          }
        })
      )

      console.log('SaleReturnItemForm - mappedData:', mappedData) // 调试信息
      formData.value = mappedData
    } else {
      formData.value = val || []
    }
  },
  { immediate: true }
)

/** 监听合同产品变化，计算合同产品总价 */
watch(
  () => formData.value,
  (val) => {
    if (!val || val.length === 0) {
      return
    }
    // 循环处理
    val.forEach((item) => {
      item.totalWeight = erpPriceMultiply(item.weight || 0, item.count || 0) // 总克重 = 克重 * 数量
      item.totalProductPrice = erpPriceMultiply(item.productPrice, item.count)
      item.taxPrice = erpPriceMultiply(item.totalProductPrice, item.taxPercent / 100.0)
      if (item.totalProductPrice != null) {
        item.totalPrice = item.totalProductPrice + (item.taxPrice || 0)
      } else {
        item.totalPrice = undefined
      }
    })
  },
  { deep: true }
)

/** 合计 */
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (['count', 'totalProductPrice', 'taxPrice', 'totalPrice'].includes(column.property)) {
      const sum = getSumValue(data.map((item) => Number(item[column.property])))
      sums[index] =
        column.property === 'count' ? erpCountInputFormatter(sum) : erpPriceInputFormatter(sum)
    } else {
      sums[index] = ''
    }
  })

  return sums
}

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    productId: undefined,
    productUnitName: undefined, // 品目-categoryName
    productBarCode: undefined, // 金成色-goldFinenessName
    productCategoryName: undefined, // 品类-unitName
    productPrice: undefined,
    stockCount: undefined, // 库存-stock
    weight: undefined, // 克重
    count: 1,
    totalWeight: undefined, // 总克重
    totalProductPrice: undefined,
    taxPercent: undefined,
    taxPrice: undefined,
    totalPrice: undefined,
    remark: undefined
  }
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index: number) => {
  formData.value.splice(index, 1)
}

/** 处理产品变更 */
const onChangeProduct = (productId, row) => {
  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    row.productUnitName = product.categoryName // 品目
    row.productBarCode = product.goldFinenessName // 金成色
    row.productCategoryName = product.unitName // 品类
    row.stockCount = product.stock // 直接使用产品数据中的库存
    row.weight = product.weight // 克重
    row.productPrice = product.salePrice
  }
}

/** 仓库变更处理 */
const onChangeWarehouse = (warehouseId, row) => {
  row.warehouseId = warehouseId
  // 重新获取产品信息
  if (row.productId) {
    onChangeProduct(row.productId, row)
  }
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}
defineExpose({ validate, formData })

/** 初始化 */
onMounted(async () => {
  warehouseList.value = await GoldWarehouseApi.getGoldWarehouseEnabledSimpleList()
  defaultWarehouse.value = warehouseList.value.find((item) => item.status === 1) // 金料仓库使用status字段
  productList.value = await ProductApi.getProductSimpleList()
  // 默认添加一个
  if (formData.value.length === 0) {
    handleAdd()
  }
})
</script>
